#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <stdlib.h>
#include <sys/wait.h>

void ChildRun()
{
  int cnt = 5; 
  while(cnt)
  {
    printf("I am child process, pid: %d, ppid: %d, cnt : %d\n", getpid(), getppid(), cnt);
    sleep(1);
    cnt--;
  }
}

int main()
{
  printf("I am father, pid: %d, ppid: %d\n", getpid(), getppid());

  pid_t id = fork();
  if(id == 0)
  {
    // ChildRun
    ChildRun();
    printf("child quit ...\n");
    exit(123);
  }
  sleep(7); // 方便观察现象

  // 因为子进程全部exit，所以不用else
  // father
  //pid_t rid = wait(NULL);
  int status = 0;
  pid_t rid = waitpid(id, &status, 0);
  if(rid > 0)
  {
    printf("wait success. rid: %d\n", rid);
  }
  // printf("father quit...\n");
  sleep(3);
  printf("father quit, status: %d, child quid code: %d, child quit signal: %d\n", status, (status >> 8) & 0xFF, status & 0x7F);

  return 0;
}

//int main()
//{
//  printf("hello Y!!!");
//  sleep(2);
//
//  //exit(3);
//  _exit(3);
//}

enum 
{
  Success = 0,
  Div_zero,
  Mod_zero,
};

int exit_code = Success;

const char *CodeToErrString(int code)
{
  switch(code)
  {
    case Success:
        return "Success";
    case Div_zero:
        return "div zero!!";
    case Mod_zero:
        return "mod zero!!";
    default:
        return "unknow error!!!";
  }
}

int Div(int x, int y)
{
//    if( y == 0 )
//    {
//      exit_code = Div_zero;
//      return -1;
//    }
//    else
//    {
      return x / y;
//    }
}

//int main()
//{
//   // int *p = NULL;
//    while(1)
//    {
//      printf("I am a process, pid : %d\n", getpid());
//      sleep(1);
//      exit(123);
//     // *p = 100; // 伪造野指针问题
//    }
//
////    int result = Div(10, 120);
////    printf("result: %d [%s]\n", result, CodeToErrString(exit_code));
////    result = Div(10, 0);
////    printf("result: %d [%s]\n", result, CodeToErrString(exit_code));
////    int errcode = 0;
////    for(; errcode <= 255; ++errcode)
////    {
////      printf("%d : %s\n", errcode, strerror(errcode));
////    }
////
////    printf("I am a process, pid: %d, ppid: %d\n", getpid(), getppid());
//    sleep(2);
//
//    return exit_code;
//}
